package com.bingbaihanji.springbooth2basedemo.config;

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.List;


@Configuration
@EnableWebMvc
@Slf4j
public class WebMvcConfigurers implements WebMvcConfigurer {

    /**
     * @MethodName: configureMessageConverters
     * @Author 冰白寒祭
     * @Description: //信息转换器 使用 FastJsonHttpMessageConverter 来替换 Spring MVC
     * 默认的 HttpMessageConverter 以提高 @RestController @ResponseBody @RequestBody
     * 注解的 JSON序列化和反序列化速度。
     * @Date: 2023-11-20 23:19:32
     * @param: a
     * @return: a
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        log.info("信息转换器启动");
        //清空所有默认的转换器，不然容易受StringHttpMessageConverter的影响
//        converters.clear();

        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        //自定义配置...
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");


        config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
        config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.PrettyFormat);
        converter.setFastJsonConfig(config);

        converter.setDefaultCharset(StandardCharsets.UTF_8);
        converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
        converters.add(0, converter);
    }


}